#! /usr/bin/python

import os
import time
import sys
import re
import argparse

def replace_env_var(path):
    def get_env(match):
        return os.getenv(match.group(1))
    path = re.sub(r"\$(\w+)", get_env, path)
    return path

def replace_relative_path(base, offset=""):
    if offset != "" and re.match(r"\.", offset):
        path = os.path.join(base, offset)
    elif offset != "":
        path = offset
    else:
        path = base
    path = re.sub(r"\/.\/\/", "//", path) # /path/./aaa -> /path//a
    path = re.sub(r"\/+", "/", path) #/path///aa//b -> /path/a/b
    while re.search(r"\w+\/\.\.\/", path):
        path = re.sub(r"\w+\/\.\.\/", "",path) #/path/aa/../b -> /path/b
    return path

def path_trans(path, offset=""):
    return replace_relative_path(replace_env_var(path), offset)

def process_list(lst, root):
    file_list = []
    lst = lst.strip()
    lst = path_trans(lst)
    #file_list.append(lst)
    (filepath, filename) = os.path.split(lst)
    with open (lst, "r") as handle:
        for line in handle:
            line = re.sub(r"\/\/.*", "", line)
            if line != "":
                re0 = re.match(r"\+incdir\+(.*)", line)
                re1 = re.match(r"\-f\s+(.*)", line)
                re2 = re.match(r"-v", line)
                re3 = re.match(r"-y", line)
                if re0:
                    path = path_trans(root, re0.group(1))
                    file_list.append(path)
                elif re1:
                    path = path_trans(root, re1.group(1))
                    file_list.extend(process_list(path))
                elif not re2 and not re3:
                    path = line.strip()
                    path = path_trans(root, path)
                    file_list.append(path)
    return file_list

def main():
    lst = sys.argv[1]
    path, file= os.path.split(lst)
    rtl_list = process_list(lst, path)
    with open ("../script/files.tcl", "w") as handle:
        handle.write("set files { \n")
        for line in rtl_list:
            handle.write("{0} \n".format(line))
        handle.write("}")

if __name__ == '__main__':
    main()
